/**
 * 断卡行动分析器 (SIM Swap/Drop)
 * 检测短寿命号码、频繁换卡等行为
 */
class SimSwapAnalyzer extends BaseAnalyzer {
    constructor(caseId) {
        super(caseId);
        this.name = '断卡行动';
        this.description = '检测短寿命号码（"日抛卡"、"周抛卡"）及频繁更换号码的行为';
    }

    /**
     * 执行断卡行动分析
     * @param {Object} params { maxLifespanDays: 7, minCalls: 5 }
     */
    async analyze(params = {}) {
        const maxLifespanDays = params.maxLifespanDays || 7;
        const minCalls = params.minCalls || 5;

        // 逻辑：
        // 检测对方号码的生命周期（在话单中出现的时间跨度）
        // 如果时间跨度很短（< 7天）但通话频次较高，疑似"一次性"卡

        const sql = `
            SELECT 
                opp_user_number,
                COUNT(*) as total_calls,
                MIN(start_time) as first_seen,
                MAX(start_time) as last_seen,
                CAST((julianday(MAX(start_time)) - julianday(MIN(start_time))) AS INTEGER) as lifespan_days
            FROM call_records
            WHERE case_id = ?
            GROUP BY opp_user_number
            HAVING lifespan_days <= ? AND total_calls >= ?
            ORDER BY lifespan_days ASC, total_calls DESC
            LIMIT 50
        `;

        const result = await this.runQuery(sql, [this.caseId, maxLifespanDays, minCalls]);

        if (!result.success) {
            return this.createResult('sim_swap', this.name, [], '查询失败: ' + result.message, 'danger');
        }

        const data = result.data;
        const summary = data.length > 0
            ? `发现 ${data.length} 个短寿命号码（生命周期 < ${maxLifespanDays}天），疑似"日抛卡"或"周抛卡"`
            : '未发现明显的短寿命号码';

        const level = data.length > 5 ? 'warning' : (data.length > 0 ? 'info' : 'info');

        return this.createResult('sim_swap', this.name, data, summary, level);
    }

    renderResult(data) {
        if (!data || data.length === 0) {
            return '<div class="empty-result" style="padding:40px; text-align:center; color:#999;">✓ 未发现短寿命号码</div>';
        }

        let html = `
      <div class="result-summary" style="padding:15px; background:#f4f4f5; border-left:4px solid #909399; margin-bottom:15px;">
        <strong>💳 发现 ${data.length} 个短寿命号码</strong>
        <p style="margin:5px 0 0; font-size:0.9rem;">这些号码在话单中出现时间极短，可能为"黑卡"或临时卡</p>
      </div>
      
      <table class="analysis-result-table" style="width:100%; border-collapse:collapse; font-size:0.9rem;">
        <thead style="background:#f5f7fa;">
          <tr>
            <th style="padding:10px; border:1px solid #e0e0e0;">对方号码</th>
            <th style="padding:10px; border:1px solid #e0e0e0; text-align:center;">生命周期(天)</th>
            <th style="padding:10px; border:1px solid #e0e0e0; text-align:center;">通话次数</th>
            <th style="padding:10px; border:1px solid #e0e0e0;">首次出现</th>
            <th style="padding:10px; border:1px solid #e0e0e0;">最后出现</th>
          </tr>
        </thead>
        <tbody>
    `;

        data.forEach((row, index) => {
            const rowStyle = index % 2 === 0 ? 'background:#fafafa;' : '';
            html += `<tr style="${rowStyle}">`;
            html += `<td style="padding:8px; border:1px solid #e0e0e0; font-family:monospace;">${row.opp_user_number || ''}</td>`;
            html += `<td style="padding:8px; border:1px solid #e0e0e0; text-align:center; font-weight:bold; color:#f56c6c;">${row.lifespan_days}</td>`;
            html += `<td style="padding:8px; border:1px solid #e0e0e0; text-align:center;">${row.total_calls}</td>`;
            html += `<td style="padding:8px; border:1px solid #e0e0e0; font-size:0.85rem;">${this.formatDate(row.first_seen)}</td>`;
            html += `<td style="padding:8px; border:1px solid #e0e0e0; font-size:0.85rem;">${this.formatDate(row.last_seen)}</td>`;
            html += '</tr>';
        });

        html += '</tbody></table>';
        return html;
    }
}

window.SimSwapAnalyzer = SimSwapAnalyzer;
